﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading.Tasks;
using AutoMapper;
using KC.Framework.Exceptions;
using KC.Framework.Extension;
using KC.Framework.SecurityHelper;
using KC.Framework.Tenant;
using KC.DataAccess.Account;
using KC.DataAccess.Account.Repository;
using KC.Framework.Base;
using KC.Model.Account;
using KC.Service.Account.EventHandlers;
using KC.Service.Core.EFService;
using KC.Service.Core.Events;
using KC.Service.Core.Extension;
using KC.DTO.Account;
using KC.DTO.Core;
using KC.Service.Storage;
using KC.ThirdParty;
using Microsoft.AspNetCore.Identity;
using KC.Domain.Core.IRepository;
using Microsoft.Extensions.Logging;
using KC.Service.Core.WebApiService.Business;

namespace KC.Service.Account
{
    public sealed class AccountService : EFServiceBase, IAccountService
    {
        #region Db Repository
        private ComAccountContext _dbContext;
        private IUserRepository _userRepository;
        private IDbRepository<UserTracingLog> _userTracingLogRepository;

        private UserManager<User> _userManager { get { return new UserManager<User>(_userRepository, null, null, null, null, null, null, null, null);  } }
        #endregion

        //public AccountService(
        //    Tenant tenant)
        //    : base(tenant, null)
        //{
        //}

        public AccountService(
            Tenant tenant,
            IAccountApiService accountApiService,
            ITenantUserApiService tenantUserApiService,
            IConfigApiService configApiService,
            ComAccountContext dbContext,
            IUserRepository userRepository,
            IDbRepository<UserTracingLog> userTracingLogRepository,
            System.Net.Http.IHttpClientFactory clientFactory,
            Microsoft.Extensions.Logging.ILogger<AccountService> logger)
            : base(tenant, accountApiService, tenantUserApiService, configApiService, clientFactory, logger)
        {
            _dbContext = dbContext;
            _userRepository = userRepository;
            _userTracingLogRepository = userTracingLogRepository;
        }

        #region User

        public async Task<bool> ExistUserEmail(string email)
        {
            var isValid = StringExtensions.IsEmail(email);
            if (!isValid || string.IsNullOrEmpty(email)) return false;

            Expression<Func<User, bool>> predicate = m => m.Email.Equals(email, StringComparison.OrdinalIgnoreCase);

            return await _userRepository.ExistUserByFilterAsync(predicate);
        }
        public async Task<bool> ExistUserPhone(string phone)
        {
            var isValid = StringExtensions.IsMobile(phone);
            if (!isValid || string.IsNullOrEmpty(phone)) return false;

            Expression<Func<User, bool>> predicate = m => m.PhoneNumber.Equals(phone, StringComparison.OrdinalIgnoreCase);

            return await _userRepository.ExistUserByFilterAsync(predicate);
        }
        public async Task<bool> ExistUserName(string userName)
        {
            var isValid = userName.Length >= 2 && userName.Length <= 15;
            if (!isValid || string.IsNullOrEmpty(userName)) return false;

            Expression<Func<User, bool>> predicate = m => m.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase);

            return await _userRepository.ExistUserByFilterAsync(predicate);
        }

        public List<UserDTO> GetAllUsersWithRolesAndOrgs()
        {
            return Mapper.Map<List<UserDTO>>(_userRepository.FindAllDetailUsers());
        }
        public List<UserDTO> GetUsersByRoleIds(List<string> roleIds)
        {
            var data = _userRepository.FindUsersByRoleIds(roleIds);
            return Mapper.Map<List<UserDTO>>(data);
        }
        public List<UserDTO> GetUsersByIds(List<string> userIds)
        {
            var data = _userRepository.FindUsersWithOrgsByIds(userIds);
            return Mapper.Map<List<UserDTO>>(data);
        }

        public List<UserDTO> GetUsersByNames(List<string> names)
        {
            var data = _userRepository.FindUsersByNames(names);
            return Mapper.Map<List<UserDTO>>(data);
        }
        public List<UserDTO> GetUsersByEmails(List<string> names)
        {
            var data = _userRepository.FindUsersByEmails(names);
            return Mapper.Map<List<UserDTO>>(data);
        }
        public List<UserDTO> FindAllUsersNoInclude()
        {
            var data = _userRepository.FindAllSimpleUsers().ToList();
            return Mapper.Map<List<UserDTO>>(data);
        }
        public List<UserDTO> FindAllUsersNoIncludeByUserId(List<string> userIds)
        {
            var data = _userRepository.FindUsersByIds(userIds).ToList();
            return Mapper.Map<List<UserDTO>>(data);
        }


        //paging分页参数
        public PaginatedBaseDTO<UserDTO> GetPaginatedUsersByFilter(int pageIndex, int pageSize, string email, string phone, string name, string statType, PositionLevel? positionLevel)
        {
            Expression<Func<User, bool>> predicate = m => true;
            if (!string.IsNullOrWhiteSpace(email))
            {
                predicate = predicate.And(m => m.Email.Contains(email));
            }
            if (!string.IsNullOrWhiteSpace(phone))
            {
                predicate = predicate.And(m => m.PhoneNumber.Contains(phone));
            }
            if (!string.IsNullOrWhiteSpace(name))
            {
                predicate = predicate.And(m => m.DisplayName.Contains(name));
            }
            if (!string.IsNullOrWhiteSpace(statType))
            {
                int stat = Convert.ToInt32(statType);
                predicate = predicate.And(m => m.Status.Equals(stat));
            }
            else
            {
                predicate = predicate.And(m => m.Status == WorkFlowStatus.Approved);
            }
            if (positionLevel != null)
            {
                predicate = predicate.And(m => m.PositionLevel == positionLevel);
            }
            var data = _userRepository.FindPagenatedUsersByFilter(pageIndex, pageSize, predicate, "CreateDate", false, true);
            var total = data.Item1;
            var rows = data.Item2;
            var model = new PaginatedBaseDTO<UserDTO>(pageIndex, pageSize, total, Mapper.Map<List<UserDTO>>(rows).ToList());
            return model;
        }
        //重新分页
        public PaginatedBaseDTO<UserDTO> GetPaginatedUsersPagedAgain(int pageIndex, int pageSize, List<UserDTO> list)
        {
            var total = list.Count();
            var rows = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var model = new PaginatedBaseDTO<UserDTO>(pageIndex, pageSize, total, Mapper.Map<List<UserDTO>>(rows));
            return model;
        }
        public PaginatedBaseDTO<UserDTO> GetPaginatedUsersByOrgIds(int pageIndex, int pageSize, List<int> list)
        {
            var data = _userRepository.GetPaginatedUsersByOrgIds(pageIndex, pageSize, list);
            var total = data.Item1;
            var rows = data.Item2;
            var model = new PaginatedBaseDTO<UserDTO>(pageIndex, pageSize, total, Mapper.Map<List<UserDTO>>(rows).ToList());
            return model;
        }

        public UserSimpleDTO GetSimpleUserWithOrgAndRoleNameByUserId(string userId)
        {
            var model = _userRepository.GetUserWithOrgsAndRolesById(userId);
            return Mapper.Map<UserSimpleDTO>(model);
        }
        public UserDTO GetUserWithOrganizationsByUserId(string userId)
        {
            var model = _userRepository.GetUserWithOrgsAndRolesById(userId);
            return Mapper.Map<UserDTO>(model);
            //return new UserInfoMapper().Map(model);
        }
        public UserDTO GetUserByUserName(string userName)
        {
            var model = _userManager.FindByNameAsync(userName).Result;
            return Mapper.Map<UserDTO>(model);
        }
        /// <summary>
        /// 根据Id查询数据  跟GetUserById区别,查出OrganizationNames
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public UserDTO GetUserCheckId(string userId)
        {
            Expression<Func<User, bool>> predicate = m => m.Id == userId;

            var data = _userRepository.FindPagenatedUsersByFilter(1, 10, predicate, "CreateDate", false, false);
            var total = data.Item1;
            var rows = data.Item2;
            var model = new PaginatedBaseDTO<UserDTO>(1, 10, total, Mapper.Map<List<UserDTO>>(rows)).rows.FirstOrDefault();
            return model;
        }

        public UserContactInfoDTO GetUserContactInfoById(string userId)
        {
            var data = _userManager.FindByIdAsync(userId).Result;
            return data.MapTo<UserContactInfoDTO>();
        }

        public Task<IdentityResult> CreateUser(UserDTO data, string operatorId, string operatorName,
            string[] organizations, string gussourl)
        {
            string[] Snum = data.UserName.Split(',');
            data.UserName = Snum[Snum.Count() - 1];
            var alldate = _userRepository.FindAllSimpleUsers().ToList();
            if (alldate.Any(m => m.ReferenceId1 == data.ReferenceId1))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.ReferenceId1 + "】员工号");
            }
            if (alldate.Any(m => m.UserName == data.UserName))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.UserName + "】登录名");
            }
            if (alldate.Any(m => m.PhoneNumber == data.PhoneNumber))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.PhoneNumber + "】手机号");
            }
            if (alldate.Any(m => m.Email == data.Email))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.Email + "】邮箱");
            }
            //if (alldate.Any(m => m.Telephone == data.Telephone && m.Telephone != null))
            //{
            //    throw new BusinessPromptException("系统已经注册了【" + data.Telephone + "】座机号");
            //}

            //创建用户个数限制
            CreateUserLimit();

            data.UserId = Guid.NewGuid().ToString();
            //data.MemberId = StoredProcedureHelper.GetSeedByType(SeedType.Member).SeedValue;

            var model = Mapper.Map<User>(data);
            model.Recommended = Tenant.TenantName;
            model.UserName = !string.IsNullOrWhiteSpace(data.UserName) ? data.UserName : data.Email;
            model.CreateDate = DateTime.UtcNow;
            model.Status = WorkFlowStatus.Approved;
            var password = EncryptPasswordUtil.GetRandomString(); //生成用户的初始化登录密码

            var result = _userManager.CreateAsync(model, password);

            if (result.Result != null && result.Result.Succeeded)
            {
                var organizationId = organizations.Select(m => Int32.Parse(m)).ToList();
                _userRepository.UpdateUserInOrganizations(organizationId, data.UserId);
                Task.Factory.StartNew(() =>
                {
                    //创建用户成功发送短信
                    bool isSucceedSendSms = CreateUserSendSms(data);

                    //创建用户成功发送邮件
                    var inputParameter = new
                    {
                        UserDisplayName = data.DisplayName,
                        UserAccount = data.Email,
                        UserPassword = password,
                        AdministratorName = operatorName,
                        gurl = gussourl

                    };

                    //var createUserMessageUtil =
                    //    new MessageUtil(new UserTemplateGenerator(Tenant, SerializeHelper.ToJson(inputParameter),
                    //        UserTemplateGenerator.User_Created));
                    bool isSucceedSendEmail = true;

                    const string logMessage = "{0}在{1}进行了以下操作：{2}！";
                    var log = new UserTracingLog
                    {
                        OperatorId = operatorId,
                        Operator = operatorName,
                        OperateDate = DateTime.UtcNow,
                        Type = (isSucceedSendEmail || isSucceedSendSms)
                            ? Framework.Base.ProcessLogType.Success
                            : Framework.Base.ProcessLogType.Failure,
                        Remark = string.Format(logMessage,
                            operatorName,
                            DateTime.UtcNow.ToLocalDateTimeStr("yyyy-MM-dd HH:mm:ss"),
                            "创建了用户（" + model.Id + ", " + model.UserName + ")")
                    };
                    _userTracingLogRepository.Add(log);

                    //ServiceEvents.Register(new UserCreatedHandler(Tenant, data, password));
                });
            }
            else if (result.Result != null && !result.Result.Succeeded)
            {
                throw new BusinessPromptException(string.Join(",", result.Result.Errors));
            }

            return result;
        }
        public bool UpdateUser(UserDTO data, string operatorId, string operatorName, string[] organizations)
        {
            string[] Snum = data.UserName.Split(',');
            data.UserName = Snum[Snum.Count() - 1];
            //同名验证判定
            var alldate = _userRepository.FindAllSimpleUsers().Where(m => m.Id != data.UserId).ToList();

            //var count_email=alldate.Where(m => m.Email == data.Email).ToList();
            //var count_phone=alldate.Where(m => m.PhoneNumber == data.PhoneNumber).ToList();
            if (alldate.Any(m => m.UserName == data.UserName))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.UserName + "】登录名");
            }
            if (alldate.Any(m => m.ReferenceId1 == data.ReferenceId1))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.ReferenceId1 + "】用户编号");
            }
            if (alldate.Any(m => m.PhoneNumber == data.PhoneNumber))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.PhoneNumber + "】手机号");
            }
            if (alldate.Any(m => m.Email == data.Email))
            {
                throw new BusinessPromptException("系统已经注册了【" + data.Email + "】邮箱");
            }

            var model = Mapper.Map<User>(data);
            var organizationIds = organizations.Select(m => int.Parse(m)).ToList();
            _userRepository.UpdateUser(model, organizationIds, false);

            const string logMessage = "{0}进行了以下操作：{1}！";
            var log = new UserTracingLog
            {
                OperatorId = operatorId,
                Operator = operatorName,
                OperateDate = DateTime.UtcNow,
                Type = Framework.Base.ProcessLogType.Success,
                Remark = string.Format(logMessage,
                    operatorName,
                    "更新了用户（" + model.UserName + ")相关信息")
            };
            _userTracingLogRepository.Add(log, false);

            //using (var scope = ServiceProvider.CreateScope())
            {
                //var dbContext = scope.ServiceProvider.GetRequiredService<ComAccountContext>();
                var result = _dbContext.SaveChanges() > 0;
                if (result)
                {
                    ServiceEvents.Register(new UserModifiedHandler(data));
                }
            }
            return true;
        }
        public bool RemoveUserById(string id, string operatorId, string operatorName, Guid appId)
        {
            return _userRepository.RemoveUserById(id, operatorId, operatorName, appId);
        }
        public bool UpdateRoleInUser(string userId, List<string> addList, string operatorId, string operatorName)
        {
            return _userRepository.SaveRoleInUser(userId, addList, operatorId, operatorName);
        }

        #endregion

        #region DownLoad User Excel && Import User data from Excel

        public bool ImportUserDataFromExcel(Stream stream)
        {
            var rows = new NPOIExcelReader(stream).GetWorksheetRowListData();
            var seed = base.GenerateIdByName(Core.SeedType.Member, rows.Count);
            var min = 10;
            var codePrefix = "ur";

            var newUsers = new List<User>();
            for (var i = 0; i < rows.Count; i++)
            {
                var code = codePrefix + (min + i).ToString().PadLeft(5, '0');

                #region 拼装AspNetUser对象
                var user = new User()
                {
                    Id = Guid.NewGuid().ToString(),
                    MemberId = code,
                    EmailConfirmed = true,
                    PhoneNumberConfirmed = true,
                    PasswordHash = "AMaw+mzoTNm+VnSIxMrkvPNFWoXu2f84SdacTW8S4UhKm2L63xY8fUVcBlSZh1UZVQ==",
                    SecurityStamp = "4f67bcf7-1ada-415b-924e-eedae494a32c",
                    PositionLevel = PositionLevel.Staff,
                    IsDefaultMobile = true,
                    CreateDate = DateTime.UtcNow,
                };

                var row = rows[i];
                foreach (var cell in row)
                {
                    switch (cell.ColumnName)
                    {
                        case "Id":
                            if (!string.IsNullOrWhiteSpace(cell.CellValue))
                            {
                                user.Id = cell.CellValue;
                            }
                            break;
                        case "用户编号":
                            if (!string.IsNullOrWhiteSpace(cell.CellValue))
                            {
                                user.MemberId = cell.CellValue;
                            }
                            break;
                        case "用户名称":
                            if (!string.IsNullOrWhiteSpace(cell.CellValue))
                            {
                                user.DisplayName = cell.CellValue;
                            }
                            break;
                        case "用户邮箱":
                            if (!string.IsNullOrWhiteSpace(cell.CellValue))
                            {
                                user.UserName = cell.CellValue;
                                user.Email = cell.CellValue;
                            }
                            break;
                        case "用户手机":
                            if (!string.IsNullOrWhiteSpace(cell.CellValue))
                            {
                                user.PhoneNumber = cell.CellValue;
                            }
                            break;
                        case "用户加密密码":
                            if (!string.IsNullOrWhiteSpace(cell.CellValue))
                            {
                                user.PasswordHash = cell.CellValue;
                            }
                            break;
                        case "加密时间戳":
                            if (!string.IsNullOrWhiteSpace(cell.CellValue))
                            {
                                user.SecurityStamp = cell.CellValue;
                            }
                            break;
                    }
                }
                #endregion

                newUsers.Add(user);
            }

            if (!newUsers.Any())
                return true;

            var dbUsers = _userRepository.FindAllDetailUsers();
            foreach (var user in newUsers.ToList())
            {
                var dbCustomer =
                    dbUsers.FirstOrDefault(
                        m => m.Id != null && m.Id.Equals(user.Id, StringComparison.OrdinalIgnoreCase));
                if (dbCustomer != null)
                {
                    //dbCustomer.MemberId = user.MemberId;
                    dbCustomer.DisplayName = user.DisplayName;
                    dbCustomer.UserName = user.UserName;
                    dbCustomer.Email = user.Email;
                    dbCustomer.PhoneNumber = user.PhoneNumber;
                    dbCustomer.PasswordHash = user.PasswordHash;
                    dbCustomer.SecurityStamp = user.SecurityStamp;
                    dbCustomer.ContactQQ = user.ContactQQ;
                    var properties = new[] { "DisplayName", "UserName", "Email", "PhoneNumber", "PasswordHash", "SecurityStamp", "ContactQQ" };
                    _userRepository.UpdateUser(dbCustomer, null, false);
                }
                else
                {
                    _userRepository.AddUsers(newUsers, false);
                }
            }

            //using (var scope = ServiceProvider.CreateScope())
            {
                //var dbContext = scope.ServiceProvider.GetRequiredService<ComAccountContext>();
                return _dbContext.SaveChanges() > 0;
            }
        }

        #endregion

        #region AccountApi 登录 & 绑定微信号
        public async Task<UserDTO> GetUserByWxOpenIdAsync(string openId)
        {
            var user = await _userRepository.FindByWxOpenIdAsync(openId.Trim());
            if (user == null)
                return null;

            var result = Mapper.Map<UserDTO>(user);
            var roleIds = user.UserRoles.Select(r => r.RoleId);
            var roleNames = new List<string>();
            var roles = await _userRepository.FindRolesByRoleIdsAysnc(roleIds.ToList());
            if (roles.Any())
                roleNames.AddRange(roles.Select(m => m.Name));

            result.RoleNames = roleNames;
            result.TenantName = base.Tenant.TenantName;
            return result;
        }
        public async Task<string> UpdateWxOpenIdAsync(string userId, string openId)
        {
            var user = await _userManager.FindByIdAsync(userId);
            if (user != null)
            {
                user.OpenId = openId;
                var result = await _userManager.UpdateAsync(user);
                if (result.Succeeded)
                    return string.Empty;

                return result.Errors.Select(m => m.Description).ToCommaSeparatedString();
            }

            return string.Format("未找到Id为：{0}的用户", userId);
        }

        public async Task<UserDTO> GetUserAndCheckAsync(string userName, string password)
        {
            User user = null;
            if (userName.Contains("@"))
            {
                if (userName.Trim().Equals("admin@cfwin.com", StringComparison.OrdinalIgnoreCase))
                {
                    user = await _userManager.FindByNameAsync(userName);
                }
                else
                {
                    user = await _userManager.FindByEmailAsync(userName);
                }
            }
            else if (userName.IsMobile())
            {
                user = await _userRepository.FindByPhoneAsync(userName);
            }
            else
            {
                user = await _userManager.FindByNameAsync(userName);
            }

            if (await _userManager.CheckPasswordAsync(user, password))
            {
                var result = Mapper.Map<UserDTO>(user);
                var roleIds = user.UserRoles.Select(r => r.RoleId).ToList();
                var roleNames = new List<string>();
                var roles = await _userRepository.FindRolesByRoleIdsAysnc(roleIds);
                roles.ToList().ForEach(m => roleNames.Add(m.Name));

                result.RoleNames = roleNames;
                result.TenantName = base.Tenant.TenantName;
                return result;
            }

            return null;
        }

        public async Task<UserDTO> GetUserAndCheckAsync(string openId)
        {
            User user = await _userRepository.GetUserByFilterAsync(m => m.OpenId.Equals(openId));
            if (user == null)
                return null;
            var result = Mapper.Map<UserDTO>(user);
            var roleIds = user.UserRoles.Select(r => r.RoleId).ToList();
            var roleNames = new List<string>();
            var roles = await _userRepository.FindRolesByRoleIdsAysnc(roleIds);
            roles.ToList().ForEach(m => roleNames.Add(m.Name));

            result.RoleNames = roleNames;
            result.TenantName = base.Tenant.TenantName;
            return result;
        }
        #endregion

        #region Password

        public async Task<IdentityResult> ChangePasswordAsync(string userId, string currentPassword, string newPassword)
        {
            var user = await _userManager.FindByIdAsync(userId);
            var cResult = await _userManager.ChangePasswordAsync(user, currentPassword, newPassword);
            if(cResult.Succeeded)
            {
                await _userManager.UpdateAsync(user);
            }

            return cResult;
        }

        public async Task<IdentityResult> ChangeAdminRawInfoAsync(string newPassword, string adminEmail, string adminPhone)
        {
            var userId = RoleConstants.AdminUserId;
            var user = await _userManager.FindByIdAsync(userId);
            var result = await _userManager.ChangePasswordAsync(user, "123456", newPassword);
            if (!result.Succeeded)
                return result;

            if (user != null)
            {
                user.Email = adminEmail;
                user.PhoneNumber = adminPhone;
                return await _userManager.UpdateAsync(user);
            }
            return new IdentityResult();
        }

        public async Task<IdentityResult> ChangeMailPhoneAsync(string userId, string email, string phone)
        {
            var user = await _userManager.FindByIdAsync(userId);
            if (user != null)
            {
                user.Email = email;
                user.PhoneNumber = phone;
                return await _userManager.UpdateAsync(user);
            }
            return new IdentityResult();
        }

        public string HashPassword(string password)
        {
            byte[] salt;
            byte[] buffer2;
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
            {
                salt = bytes.Salt;
                buffer2 = bytes.GetBytes(0x20);
            }
            byte[] dst = new byte[0x31];
            Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
            Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
            return Convert.ToBase64String(dst);
        }

        [MethodImpl(MethodImplOptions.NoOptimization)]
        private static bool ByteArraysEqual(byte[] a, byte[] b)
        {
            if (object.ReferenceEquals(a, b))
            {
                return true;
            }
            if (((a == null) || (b == null)) || (a.Length != b.Length))
            {
                return false;
            }
            bool flag = true;
            for (int i = 0; i < a.Length; i++)
            {
                flag &= a[i] == b[i];
            }
            return flag;
        }
        #endregion

        #region utils
        /// <summary>
        /// 创建用户发送短信
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private bool CreateUserSendSms(UserDTO data)
        {
            long phone;
            var isSucceed = false;
            var smsContent = string.Format("【财富共赢】尊敬的{0}：您的产融协作员工账号已创建成功, 详情已发送至您的{1}，请登录查看。", data.DisplayName,
                data.Email);
            if (long.TryParse(data.PhoneNumber, out phone))
            {
                var smsInfo = new Model.Storage.Queue.SmsInfo
                {
                    Tenant = data.TenantName,
                    Type = KC.Framework.Base.SmsType.Marketing,
                    Phone = new List<long> { phone },
                    SmsContent = smsContent
                };
                isSucceed = new StorageQueueService().InsertSmsQueue(smsInfo);
                Logger.LogInformation((isSucceed ? "插入短信队列成功，短信内容：" : "插入短信队列失败，短信内容：") + smsContent);
            }
            return isSucceed;
        }

        /// <summary>
        /// 创建用户发送邮件
        /// </summary>
        /// <param name="data"></param>
        /// <param name="password"></param>
        /// <param name="operatorName"></param>
        /// <returns></returns>
        private bool CreateUserSendEmail(UserDTO data, string password, string operatorName)
        {
            var emailBody = string.Format(
               @"<!doctype html><html lang='en'><head><meta charset='UTF-8'><title></title><style>*,html,body{{margin:0;padding:0}}.divdiv{{width:538px;position:relative;margin:0 auto;background:#17212E;padding:20px;padding-top:0}}table{{width:100%;background:#454d5b;text-align:center;margin:0 auto;margin-top:50px;margin-bottom:50px;border-collapse:collapse}}.p_white{{color:#fff}}table tr td:first-child{{text-align:left;width:33%}}table tr td{{text-align:left;padding:9px;color:#fff;min-width:136px}}table tr th{{color:#fff;padding:13px;background:#4b5761;text-align:left}}table tr td p{{word-break:break-all;color:inherit}}.app_tb tr td:first-child{{text-align:left}}tr{{border:1px solid #636363}}.tips tr{{border:none}}.tips tr td:first-child{{text-align:left}}a{{text-decoration:none;color:#fff;word-break:break-all}}.guanggao_contain{{width:100%;position:relative;float:left;margin-top:30px;margin-bottom:30px}}.guanggao_logo{{float:left;margin-left:20px;display:block;position:relative;background-position:35px 14px;color:#afafaf}}.guanggao_logo_p{{float:left;margin-left:20px;display:block;position:relative;background-position:35px 14px;color:#afafaf;margin-bottom:10px;clear:both;width:100%}}.tips{{min-height:50px;background:0 0;font-size:12px}}.guanggao_logo:hover{{color:#fff}}.title p{{ font-size: 16px; color: #c6d4df; font-family: Arial, Helvetica, sans-serif; font-weight: bold;margin: 8px;
}}</style></head><body><div class='divdiv'><div class='guanggao_contain'><a href='http://www.cfwin.com/' target='_blank' class='guanggao_logo'>
<img src=''></a></div>
   <div class='title'>
        <p> 主题：【产融协作员工账号创建成功-财富共赢】</p>
        <p>【{0}】员工【{1}】，您好！</p>
        <p>您公司的系统管理员【{2}】为您添加的产融协作员工账号已创建成功。</p>
    </div>
    <table> <tr><td> <p>公司名称:</p></td><td> <p>{0}</p></td></tr><tr><td><p>租户代码:</p></td><td><p>{3}</p></td></tr>
        <tr><td><p>帐号:</p></td><td><p>{4}</p></td></tr><tr><td><p>初始密码:</p></td><td><p>{5}</p></td></tr>
    </table>
  <table class='tips'>
        <tr>
            <td>
                <h3>登陆地址：<a href='http://sso.cfwin.com'>http://sso.cfwin.com</a>。请登录后立即修改密码，如遇问题，请与公司系统管理员联系。</h3>
            </td>
        </tr><tr><td><br></td></tr></table></div></body></html>", Tenant.TenantDisplayName, data.DisplayName, operatorName, Tenant.TenantName, data.Email, password);

            var mail = new Model.Storage.Queue.EmailInfo
            {
                Tenant = Tenant.TenantName,
                UserId = data.UserId,
                EmailTitle = "创建登陆用户成功",
                EmailBody = emailBody,
                SendTo = new List<string> { data.Email }
            };
            //var config = EmailUtil.GetTenantEmailConfig(Tenant);
            //var isSucceed = EmailUtil.Send(config, mail.EmailTitle, mail.EmailBody, mail.SendTo, mail.CcTo);
            //var isSucceed = new StorageQueueService().InsertEmailQueue(mail);//使用队列(不针对租户)
            //var isSucceed = new TenantStorageQueueService(Tenant).InsertEmailQueue(mail); //使用队
            //Logger.LogInformation((isSucceed ? "插入Email队列成功，邮件内容：" : "插入Email队列失败，邮件内容：") + emailBody);
            return true;
        }

        private void CreateUserLimit()
        {
            var limit = "15,50";
            var users = _userRepository.FindAllDetailUsers();
            int count;
            if (Tenant.Version == Framework.Tenant.TenantVersion.Standard)
            {
                var standardTenantCount = limit.Split(',')[0];
                if (int.TryParse(standardTenantCount, out count))
                {
                    if (users.Count >= count)
                    {
                        throw new BusinessPromptException(string.Format("标准版租户创建用户不能超过{0}个", count));
                    }
                }
            }
            if (Tenant.Version == Framework.Tenant.TenantVersion.Professional)
            {
                var professionalTenantCount = limit.Split(',')[1];
                if (int.TryParse(professionalTenantCount, out count))
                {
                    if (users.Count >= count)
                    {
                        throw new BusinessPromptException(string.Format("专业版租户创建用户不能超过{0}个", count));
                    }
                }
            }
        }

        #endregion
        
    }

}
